/*
 * Copyright (C) 2009 Leandro Aparecido <lehphyro@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.metalframework.validation;

import static org.metalframework.util.AnnotationUtils.*;

import java.util.*;

import javax.validation.*;

import org.aopalliance.intercept.*;
import org.metalframework.annotation.*;
import org.metalframework.exception.ValidationException;
import org.slf4j.*;

import com.google.common.collect.*;
import com.google.inject.*;

public class ValidationInterceptor implements MethodInterceptor {

	private static final Logger logger = LoggerFactory.getLogger(ValidationInterceptor.class);
	
	private ConstraintViolationHandler violationHandler;
	private Provider<Validator> validatorProvider;

	@Override
	public Object invoke(MethodInvocation invocation) throws Throwable {
		logger.debug("Validating parameters of invocation [{}]", invocation);

		Object[] arguments = invocation.getArguments();
		List<Validate> annotations = getParameterAnnotations(invocation.getMethod(), Validate.class);
		
		Set<ConstraintViolation<Object>> violations = new LinkedHashSet<ConstraintViolation<Object>>();
		for (int i = 0; i < arguments.length; i++) {
			if (arguments[i] != null && annotations.get(i) != null) {
				violations.addAll(validateArgument(arguments[i], annotations.get(i).value()));
			}
		}
		
		if (!violations.isEmpty()) {
			violationHandler.handle(ImmutableSet.copyOf(violations));
			throw new ValidationException(violations);
		}
		
		return invocation.proceed();
	}


	protected Set<ConstraintViolation<Object>> validateArgument(Object argument, Class<?>[] groups) {
		return validatorProvider.get().validate(argument, groups);
	}
	
	@Inject
	public void setViolationHandler(ConstraintViolationHandler violationHandler) {
		this.violationHandler = violationHandler;
	}
	
	@Inject
	public void setValidatorProvider(Provider<Validator> validatorProvider) {
		this.validatorProvider = validatorProvider;
	}
}
